package com.tianyang.yukuaifuzs.module.stepview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.core.content.ContextCompat;

import com.tianyang.yukuaifuzs.R;
import com.tianyang.yukuaifuzs.module.stepview.bean.StepBean;
import com.tianyang.yukuaifuzs.utils.DeviceUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Description：StepsViewIndicator 指示器
 * Created by 薛勇军 on 2018/7/10.
 */
public class HorizontalStepsViewIndicator extends View {
    //定义默认的高度   definition default height
    private int defaultStepIndicatorNum = DeviceUtil.dp2px(50);

    private float mCompletedLineHeight;//完成线的高度     definition completed line height
    private float mCircleRadius;//圆的半径  definition circle radius

    private Drawable mCompleteLine;//完成的默认图片    definition default completed icon
    private Drawable mDefaultLine;//正在进行的默认图片     definition default underway icon

    private Drawable mCompleteIcon;//完成的默认图片    definition default completed icon
    private Drawable mAttentionIcon;//正在进行的默认图片     definition default underway icon
    private Drawable mDefaultIcon;//默认的背景图  definition default unCompleted icon
    private float mCenterY;//该view的Y轴中间位置     definition view centerY position
    private float mLeftY;//左上方的Y位置  definition rectangle LeftY position
    private float mRightY;//右下方的位置  definition rectangle RightY position

    private List<StepBean> mStepBeanList;//当前有几部流程    there are currently few step
    private int mStepNum = 0;
    private float mLinePadding;//两条连线之间的间距  definition the spacing between the two circles

    private List<Float> mCircleCenterPointPositionList;//定义所有圆的圆心点位置的集合 definition all of circles center point list
    private Paint mUnCompletedPaint;//未完成Paint  definition mUnCompletedPaint
    private Paint mCompletedPaint;//完成paint      definition mCompletedPaint
    private Paint mTextPaint;//完成paint      definition mCompletedPaint
    private int mCompletedLineColor = Color.WHITE;//定义默认完成线的颜色      definition mCompletedLineColor
    private PathEffect mEffects;
    private int mComplectingPosition;//正在进行position   underway position
    private int mCheckPosition = -1;//选中的position   underway position

    private Path mPath;

    private OnDrawIndicatorListener mOnDrawListener;
    private OnClickSetupViewListener mOnClickSetupListener;
    private int screenWidth;//this screen width

    private List<Rect> mIconRects = new ArrayList<>();

    /**
     * 设置监听
     *
     * @param onDrawListener
     */
    public void setOnDrawListener(OnDrawIndicatorListener onDrawListener) {
        mOnDrawListener = onDrawListener;
    }

    public void setOnClickSetupListener(OnClickSetupViewListener mOnClickSetupListener) {
        this.mOnClickSetupListener = mOnClickSetupListener;
    }

    /**
     * get圆的半径  get circle radius
     *
     * @return
     */
    public float getCircleRadius() {
        return mCircleRadius;
    }


    public HorizontalStepsViewIndicator(Context context) {
        this(context, null);
    }

    public HorizontalStepsViewIndicator(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HorizontalStepsViewIndicator(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public void setDefaultStepIndicatorNum(int defaultStepIndicatorNum) {
        this.defaultStepIndicatorNum = defaultStepIndicatorNum;
        init();
    }

    /**
     * init
     */
    private void init() {
        mStepBeanList = new ArrayList<>();
        mPath = new Path();
        mEffects = new DashPathEffect(new float[]{8, 8, 8, 8}, 1);

        mCircleCenterPointPositionList = new ArrayList<>();//初始化

        mTextPaint = new Paint();
        mTextPaint.setTextSize(DeviceUtil.dp2px(11));
        mTextPaint.setTextSkewX(-0.2f);

        mUnCompletedPaint = new Paint();
        mCompletedPaint = new Paint();
        mUnCompletedPaint.setAntiAlias(true);
        mUnCompletedPaint.setStyle(Paint.Style.STROKE);
        mUnCompletedPaint.setStrokeWidth(2);

        mCompletedPaint.setAntiAlias(true);
        mCompletedPaint.setColor(mCompletedLineColor);
        mCompletedPaint.setStyle(Paint.Style.STROKE);
        mCompletedPaint.setStrokeWidth(2);

        mUnCompletedPaint.setPathEffect(mEffects);
        mCompletedPaint.setStyle(Paint.Style.FILL);

        //已经完成线的宽高 set mCompletedLineHeight
        mCompletedLineHeight = 0.07f * defaultStepIndicatorNum;
        //圆的半径  set mCircleRadius
        mCircleRadius = 0.28f * defaultStepIndicatorNum;
        //线与线之间的间距    set mLinePadding
        mLinePadding = 0.85f * defaultStepIndicatorNum;

        mCompleteIcon = ContextCompat.getDrawable(getContext(), R.drawable.ic_setup_complted);//已经完成的icon
        mAttentionIcon = ContextCompat.getDrawable(getContext(), R.drawable.shape_setup_attention);//正在进行的icon
        mDefaultIcon = ContextCompat.getDrawable(getContext(), R.drawable.ic_setup_default_icon);//未完成的icon

        mCompleteLine = ContextCompat.getDrawable(getContext(), R.drawable.ic_setup_complted_line);
        mDefaultLine = ContextCompat.getDrawable(getContext(), R.drawable.ic_setup_default_line);
    }

    public void setCheckPosition(int mCheckPosition) {
        this.mCheckPosition = mCheckPosition;
        invalidate();
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = defaultStepIndicatorNum * 2;
        if (MeasureSpec.UNSPECIFIED != MeasureSpec.getMode(widthMeasureSpec)) {
            screenWidth = MeasureSpec.getSize(widthMeasureSpec);
        }
        int height = defaultStepIndicatorNum;
        if (MeasureSpec.UNSPECIFIED != MeasureSpec.getMode(heightMeasureSpec)) {
            height = Math.min(height, MeasureSpec.getSize(heightMeasureSpec));
        }
        width = (int) (mStepNum * mCircleRadius * 2 - (mStepNum - 1) * mLinePadding);
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //获取中间的高度,目的是为了让该view绘制的线和圆在该view垂直居中   get view centerY，keep current stepview center vertical
        mCenterY = 0.5f * getHeight();
        //获取左上方Y的位置，获取该点的意义是为了方便画矩形左上的Y位置
        mLeftY = mCenterY - (mCompletedLineHeight / 2);
        //获取右下方Y的位置，获取该点的意义是为了方便画矩形右下的Y位置
        mRightY = mCenterY + mCompletedLineHeight / 2;

        mCircleCenterPointPositionList.clear();
        for (int i = 0; i < mStepNum; i++) {
            //先计算全部最左边的padding值（getWidth()-（圆形直径+两圆之间距离）*2）
            float paddingLeft = (screenWidth - mStepNum * mCircleRadius * 2 - (mStepNum - 1) * mLinePadding) / 2;
            //add to list
            mCircleCenterPointPositionList.add(paddingLeft + mCircleRadius + i * mCircleRadius * 2 + i * mLinePadding);
        }

        /**
         * set listener
         */
        if (mOnDrawListener != null) {
            mOnDrawListener.ondrawIndicator(mComplectingPosition);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        for (int i = 0; i < mIconRects.size(); i++) {
            boolean contains = mIconRects.get(i).contains((int) event.getX(), (int) event.getY());
            if (contains && mOnClickSetupListener != null) {
                mOnClickSetupListener.onSetupClickListener(i);
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mOnDrawListener != null) {
            mOnDrawListener.ondrawIndicator(mComplectingPosition);
        }
        mCompletedPaint.setColor(mCompletedLineColor);

        //-----------------------画线-------draw line-----------------------------------------------
        for (int i = 0; i < mCircleCenterPointPositionList.size() - 1; i++) {
            //前一个ComplectedXPosition
            final float preComplectedXPosition = mCircleCenterPointPositionList.get(i);
            //后一个ComplectedXPosition
            final float afterComplectedXPosition = mCircleCenterPointPositionList.get(i + 1);

            /*if (i <= mComplectingPosition && mStepBeanList.get(0).getState() != StepBean.STEP_UNDO)//判断在完成之前的所有点
            {
                Rect rect = new Rect((int) (preComplectedXPosition + mCircleRadius - 10), (int) mLeftY, (int) (afterComplectedXPosition - mCircleRadius + 10), (int) mRightY);
                //判断在完成之前的所有点，画完成的线，这里是矩形,很细的矩形，类似线，为了做区分，好看些
                mCompleteLine.setBounds(rect);
                mCompleteLine.draw(canvas);
//                canvas.drawRect(, mCompletedPaint);
            } else {
                Rect rect = new Rect((int) (preComplectedXPosition + mCircleRadius - 10), (int) mLeftY, (int) (afterComplectedXPosition - mCircleRadius + 50), (int) mRightY);
                mDefaultLine.setBounds(rect);
                mDefaultLine.draw(canvas);
            }*/

            if (i < mComplectingPosition && (mStepBeanList.get(0).getState() == StepBean.STEP_COMPLETED))//判断在完成之前的所有点
            {
                Rect rect = new Rect((int) (preComplectedXPosition + mCircleRadius - 10), (int) mLeftY, (int) (afterComplectedXPosition - mCircleRadius + 10), (int) mRightY);
                //判断在完成之前的所有点，画完成的线，这里是矩形,很细的矩形，类似线，为了做区分，好看些
                mCompleteLine.setBounds(rect);
                mCompleteLine.draw(canvas);
            } else {
                Rect rect = new Rect((int) (preComplectedXPosition + mCircleRadius - 10), (int) mLeftY, (int) (afterComplectedXPosition - mCircleRadius + 10), (int) mRightY);
                mDefaultLine.setBounds(rect);
                mDefaultLine.draw(canvas);
            }

            StepBean stepsBean = mStepBeanList.get(i);

//            XLog.st(2).e(i + "   " + stepsBean.getName() + " " + stepsBean.getState());
//            if (stepsBean.getState() == StepBean.STEP_COMPLETED) {
//                Rect rect = new Rect((int) (preComplectedXPosition + mCircleRadius - 10), (int) mLeftY, (int) (afterComplectedXPosition - mCircleRadius + 10), (int) mRightY);
//                mCompleteLine.setBounds(rect);
//                mCompleteLine.draw(canvas);
//            } else if (stepsBean.getState() == StepBean.STEP_CURRENT) {
//                Rect rect = new Rect((int) (preComplectedXPosition + mCircleRadius - 10), (int) mLeftY, (int) (afterComplectedXPosition - mCircleRadius + 10), (int) mRightY);
//                mDefaultLine.setBounds(rect);
//                mDefaultLine.draw(canvas);
//            } else {
//                Rect rect = new Rect((int) (preComplectedXPosition + mCircleRadius - 10), (int) mLeftY, (int) (afterComplectedXPosition - mCircleRadius + 10), (int) mRightY);
////                //判断在完成之前的所有点，画完成的线，这里是矩形,很细的矩形，类似线，为了做区分，好看些
//                mDefaultLine.setBounds(rect);
//                mDefaultLine.draw(canvas);
//            }
//            if (i > mComplectingPosition && mStepBeanList.get(0).getState() != StepBean.STEP_COMPLETED) {
//                Rect rect = new Rect((int) (preComplectedXPosition + mCircleRadius - 10), (int) mLeftY, (int) (afterComplectedXPosition - mCircleRadius + 10), (int) mRightY);
//                mDefaultLine.setBounds(rect);
//                mDefaultLine.draw(canvas);
//            } else {
//                Rect rect = new Rect((int) (preComplectedXPosition + mCircleRadius - 10), (int) mLeftY, (int) (afterComplectedXPosition - mCircleRadius + 10), (int) mRightY);
//                //判断在完成之前的所有点，画完成的线，这里是矩形,很细的矩形，类似线，为了做区分，好看些
//                mCompleteLine.setBounds(rect);
//                mCompleteLine.draw(canvas);
//            }
        }
        //-----------------------画线-------draw line-----------------------------------------------

        mIconRects.clear();
        //-----------------------画图标-----draw icon-----------------------------------------------
        for (int i = 0; i < mCircleCenterPointPositionList.size(); i++) {
            final float currentComplectedXPosition = mCircleCenterPointPositionList.get(i);
            Rect rect = new Rect((int) (currentComplectedXPosition - mCircleRadius), (int) (mCenterY - mCircleRadius), (int) (currentComplectedXPosition + mCircleRadius), (int) (mCenterY + mCircleRadius));

            StepBean stepsBean = mStepBeanList.get(i);

            if (i == mCheckPosition) {
                mCompletedPaint.setColor(Color.WHITE);
                canvas.drawCircle(currentComplectedXPosition, mCenterY, mCircleRadius * 1.1f, mCompletedPaint);
                mAttentionIcon.setBounds(rect);
                mAttentionIcon.draw(canvas);
                mTextPaint.setColor(ContextCompat.getColor(getContext(), R.color.white));
            } else {
                if (stepsBean.getState() == StepBean.STEP_UNDO) {
                    mDefaultIcon.setBounds(rect);
                    mDefaultIcon.draw(canvas);
                    mTextPaint.setColor(ContextCompat.getColor(getContext(), R.color.c_909090));
                } else if (stepsBean.getState() == StepBean.STEP_CURRENT) {
                    mCompletedPaint.setColor(Color.WHITE);
                    canvas.drawCircle(currentComplectedXPosition, mCenterY, mCircleRadius * 1.1f, mCompletedPaint);
                    mAttentionIcon.setBounds(rect);
                    mAttentionIcon.draw(canvas);
                    mTextPaint.setColor(ContextCompat.getColor(getContext(), R.color.white));
                } else if (stepsBean.getState() == StepBean.STEP_COMPLETED) {
                    mCompleteIcon.setBounds(rect);
                    mCompleteIcon.draw(canvas);
                    mTextPaint.setColor(ContextCompat.getColor(getContext(), R.color.white));
                }
            }

            mIconRects.add(rect);
            canvas.drawText("V" + (i + 1), currentComplectedXPosition - DeviceUtil.dp2px(7), mCenterY + DeviceUtil.dp2px(4), mTextPaint);
        }
        //-----------------------画图标-----draw icon-----------------------------------------------
    }

    /**
     * 得到所有圆点所在的位置
     *
     * @return
     */
    public List<Float> getCircleCenterPointPositionList() {
        return mCircleCenterPointPositionList;
    }

    /**
     * 设置流程步数
     *
     * @param stepsBeanList 流程步数
     */
    public void setStepNum(List<StepBean> stepsBeanList, float linePadding) {
        this.mStepBeanList = stepsBeanList;
        mStepNum = mStepBeanList.size();

        if (mStepBeanList != null && mStepBeanList.size() > 0) {
            for (int i = 0; i < mStepNum; i++) {
                StepBean stepsBean = mStepBeanList.get(i);
                {
                    if (stepsBean.getState() == StepBean.STEP_COMPLETED) {
                        mComplectingPosition = i;
                    }
                }
            }
        }

        mLinePadding = linePadding;
        requestLayout();
    }

    /**
     * 设置未完成线的颜色
     *
     * @param unCompletedLineColor
     */
    public void setUnCompletedLineColor(int unCompletedLineColor) {
//        this.mUnCompletedLineColor = unCompletedLineColor;
    }


    public void setCompletedLineHeight(float completedLineHeight) {
        this.mCompletedLineHeight = completedLineHeight;
    }

    /**
     * 设置已完成线的颜色
     *
     * @param completedLineColor
     */
    public void setCompletedLineColor(int completedLineColor) {
        this.mCompletedLineColor = completedLineColor;
    }

    /**
     * 设置默认图片
     *
     * @param defaultIcon
     */
    public void setDefaultIcon(Drawable defaultIcon) {
        this.mDefaultIcon = defaultIcon;
    }

    /**
     * 设置已完成图片
     *
     * @param completeIcon
     */
    public void setCompleteIcon(Drawable completeIcon) {
        this.mCompleteIcon = completeIcon;
    }

    public void setDefaultLine(Drawable defaultLine) {
        this.mDefaultLine = defaultLine;
    }

    /**
     * 设置正在进行中的图片
     *
     * @param attentionIcon
     */
    public void setAttentionIcon(Drawable attentionIcon) {
        this.mAttentionIcon = attentionIcon;
    }


    /**
     * 设置对view监听
     */
    public interface OnDrawIndicatorListener {
        void ondrawIndicator(int position);
    }

    public interface OnClickSetupViewListener {
        void onSetupClickListener(int lvlId);
    }
}
